package com.totoro.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.totoro.pojo.*;
import com.totoro.service.EvaluationService;
import com.totoro.service.ProductService;
import com.totoro.service.SellerService;
import lombok.SneakyThrows;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author TOTORO
 * @date 2021/7/24 14:58
 * 评价controller
 */
@Controller
@RequestMapping("/evaluation")
public class EvaluationController {

    @Autowired
    SellerService sellerService;
    @Autowired
    EvaluationService evaluationService;

    /**
     * 卖家解释
     * @param pcId
     * @param text
     * @param session
     * @return
     */
    @RequestMapping(value = "/sr_evaluation", method = RequestMethod.POST)
    @ResponseBody
    public String sellerReplyEvaluation(@RequestParam("pcId") Integer pcId, @RequestParam("text") String text, HttpSession session){
        User user = (User) session.getAttribute("user");
        int slid = sellerService.findSellerIdByUserId(user.getUserId()).getId();
        SellerReply sellerReply = new SellerReply(0, pcId, slid, text);
        // 新增解释记录
        evaluationService.addSellerReply(sellerReply);
        // 修改此订单已为已解释
        evaluationService.updateIsReply(pcId);
        return "ok";
    }

    /**
     * 高级查找所有卖家评论
     * @param paramJson
     * @param session
     * @return
     */
    @SneakyThrows
    @RequestMapping("/super_find_evaluation")
    @ResponseBody
    public String SuperFindEvaluation(@RequestParam("parJson") String paramJson, HttpSession session){
        System.err.println(paramJson);
        User user = (User) session.getAttribute("user");
        int slId = sellerService.findSellerIdByUserId(user.getUserId()).getId();
//        手动获取所有的键。。。
        String[] splits = paramJson.replaceAll("\\[", "").replaceAll("]", "").replaceAll("\\{", "").replaceAll("}", "").replaceAll("\"", "").split(",");
        String[] keys = new String[splits.length];
        for (int i = 0; i < splits.length; i++) {
            keys[i] = splits[i].split(":")[0];
        }
        Map<String, Object> mapperMap = new HashMap<>();
        mapperMap.put("true", 1);
        mapperMap.put("false", 0);
        mapperMap.put("all", null);
        mapperMap.put("sellerExplain", 0);
        mapperMap.put("9999", null);

        // 反射设置属性值
        SuperEvaluationFind model = new SuperEvaluationFind();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(paramJson);
        for (int i = 0; i < root.size(); i++) {
            for (int j = 0; j < keys.length; j++) {
                if (root.get(i).get(keys[j]) != null) {
                    Field field = model.getClass().getDeclaredField(keys[j]);
                    field.setAccessible(true);
                    if (mapperMap.containsKey(root.get(i).get(keys[j]).asText())){
                        field.set(model, mapperMap.get(root.get(i).get(keys[j]).asText()));
                    } else{
                        field.set(model, root.get(i).get(keys[j]).asText());
                    }
                }
            }
        }
        model.setSlid(slId);
        model.setIsTerm(1);
        System.out.println(model);
        int nowPage = Integer.parseInt(model.getPaginationCurrent().toString());
        int pageSize = Integer.parseInt(model.getPaginationPageSize().toString());
        // 查询分页过后的数据
        List<ProductComment> comments = evaluationService.findUserAllEvaluationBySlid(model);

        // 将页数设为空，重新查寻一遍未进行分页的
        model.setPaginationCurrent(null);
        model.setPaginationPageSize(null);
        int allCount = evaluationService.findUserAllEvaluationBySlid(model).size();
        // 调用分页pojo
        Pagination pagination = new Pagination(allCount, nowPage, pageSize);
        comments.forEach(v->v.setPagination(pagination));
        if(comments.size()>0){
            System.out.println(mapper.writeValueAsString(comments));
            return mapper.writeValueAsString(comments);
        }
        return "notData";
    }

    /**
     * 修改评论匿名状态
     * @param pcId
     * @return
     */
    @RequestMapping(value = "/updateAnonymous", method = RequestMethod.POST)
    @ResponseBody
    public String updateAnonymous(@RequestParam("pcId") int pcId){
        Integer success = evaluationService.updateEvaluationAnonymous(pcId);
        if(success > 0){
            return "success";
        }
        return "error";
    }

    /**
     * 删除产品评论图片
     * @param pcId
     * @param ciId
     * @return
     */
    @PostMapping("/deleteImage")
    @ResponseBody
    public String deleteImage(@RequestParam("pcId") int pcId, @RequestParam("ciId") int ciId){
        // 删除产品评论图片，如果所有的图片都被删除了，那么设置该评论为无图状态
        Integer tr = evaluationService.deleteEvaluationImage(ciId);
        if(tr <= 0){
            return "fail";
        }
        ProductComment productComment = evaluationService.findOneEvaluation(pcId);
        if(null == productComment.getCommentImageList() || productComment.getCommentImageList().size() <=0){
            // 设置该评论记录为无图状态
            evaluationService.updateEvaluationIsHaveImage(pcId, 0);
        }
        return "success";
    }

    /**
     * 删除产品追评图片
     * @param pcId
     * @param acId
     * @param aciId
     * @return
     */
    @PostMapping("/deleteAppendImage")
    @ResponseBody
    public String deleteAppendImage(@RequestParam("pcId") int pcId, @RequestParam("acId") int acId, @RequestParam("aciId") int aciId){
        // 删除产品评论图片，如果所有的图片都被删除了，那么设置该评论为无图状态
        Integer tr = evaluationService.deleteAppendEvaImage(aciId);
        if(tr <= 0){
            return "fail";
        }
        ProductComment productComment = evaluationService.findOneEvaluation(pcId);
        if(null == productComment.getAppendComment().getAcImages() || productComment.getAppendComment().getAcImages().size() <=0){
            // 将要设置该评论记录为无图状态
            evaluationService.updateAppendEvaIsHaveImage(acId, 0);
        }
        return "success";
    }
}
